package com.jia.adpter;

import com.jia.entity.MyRoleMap;
import com.jia.entity.Role;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jia on 2018/4/11.
 */
public class MapAdpater extends XmlAdapter<MyRoleMap[],Map<String,ArrayList<Role>>>{
    /**
     * 将对象数组转换为-》map
     * @param v
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, ArrayList<Role>> unmarshal(MyRoleMap[] v) throws Exception {
        Map<String,ArrayList<Role>> map = new HashMap<String,ArrayList<Role>>();
        for (MyRoleMap myRoleMap : v) {
            String key = myRoleMap.getKey();
            ArrayList<Role> value = myRoleMap.getValue();
            map.put(key,value);
        }
        return map;
    }

    /**
     * 将Map转换为-》对象数组
     * @param v
     * @return
     * @throws Exception
     */
    @Override
    public MyRoleMap[] marshal(Map<String, ArrayList<Role>> v) throws Exception {
        MyRoleMap[] roleMaps=new MyRoleMap[v.size()];
        int i=0;
        for (String key : v.keySet()) {

            ArrayList<Role> roles = v.get(key);
            MyRoleMap myRoleMap = new MyRoleMap();
            roleMaps[i]=myRoleMap;
            myRoleMap.setKey(key);
            myRoleMap.setValue(roles);
            i++;
        }
        return roleMaps;
    }
}
